from plotly.subplots import make_subplots
import plotly.graph_objects as go
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html


def ColNameSortByNumber(cols):  # 列表通过结尾数值进行排序
    removed_lists = []
    numberList = []
    newList = []
    col_listss = [i for i in cols]

    n = 0
    e_Keys = [
        "sum",
        "Main",
        "Boll",
        "pre",
        "rolling",
        "by%",
        "SharePrise",
        "cost",
        "sort",
    ]

    Main = []
    sums = []
    sort = []
    for col in col_listss:
        nums = col.split("_")
        num = nums[-1]
        n += 1
        if len(nums) > 1 and num not in e_Keys:
            num = int(num)
            removed_lists.append(col)
            numberList.append(num)
        else:
            if "Main" in col:
                Main.append(col)
            elif "sum" in col:
                sums.append(col)
            elif "sort" in col:
                sort.append(col)
            elif "pre" in col or "Avg" in col:
                newList.append(col)

    newList.sort()
    numberList = sorted(list(set(numberList)))
    for num in numberList:
        for col in removed_lists:
            if int(col.split("_")[-1]) == num:
                newList.append(col)
    newList.extend(Main)
    newList.extend(sums)
    newList.extend(sort)
    return newList


def addTrace(cat, df, colour, fill=None, mode="lines", text="", yaxis="y"):
    Temp = go.Scatter(
        x=df["date"],
        y=round(df[cat], 5),
        marker=dict(color=colour, size=3),
        name=cat,
        #   text=df['date'],
        mode=mode,  # ['none', 'tozeroy', 'tozerox', 'tonexty', 'tonextx', 'toself', 'tonext']
        fill=fill,
        text=text,
        line=dict(
            width=2,
            #  , dash="dash"
        ),
        yaxis=yaxis,
    )
    return Temp


def MainMaTraceAdd(cols, fig, stockdata, Colours, mode="all", Ma_Day_List=[]):
    y2, y1, y5 = 0, 0, 0

    for col in cols:
        if (
            ("_by%" in col and "sum" in col and "Boll" in col)
            or "sort" in col
            #   and "close" in col
        ):
            if "All" in col:
                fig.add_trace(addTrace(col, stockdata, Colours[y2], yaxis="y2"))
            else:
                fig.add_trace(addTrace(col, stockdata, Colours[y2], yaxis="y4"))
            y2 += 1
        elif "-" in col and "ma" in col:
            if "Main" in col:
                fig.add_trace(addTrace(col, stockdata, Colours[y2], yaxis="y2"))
                y2 += 1
        elif "ma" in col and ("Boll" and "by%") not in col:
            # continue
            # if "std" in col:
            #     stockdata[col].replace(0, np.nan, inplace=True)
            #     fig.add_trace(addTrace(col, stockdata, Colours[y5], yaxis="y5"))
            #     y5 += 1
            if mode != "all":
                if mode in col:
                    stockdata[col].replace(0, np.nan, inplace=True)
                    colNumber = int(col.split("_")[-1])
                    ma_color = Colours[Ma_Day_List.index(colNumber)]
                    fig.add_trace(addTrace(col, stockdata, ma_color, yaxis="y3"))
            # else:
            #     colNumber = int(col.split("_")[-1])
            #     ma_color = Colours[Ma_Day_List.index(colNumber)]
            #     fig.add_trace(addTrace(col, stockdata, ma_color, yaxis="y3"))
        elif "timeing" in col or "day" in col or "pre" in col:
            fig.add_trace(addTrace(col, stockdata, "gray", yaxis="y2"))
            fig.add_trace(addTrace(col, stockdata, "gray", yaxis="y4"))
            y2 += 1
    return fig


def MainRepotDetail(
    report,
    Colours,
    fig,
    colNameLists=["PE_last_year_ratio", "P/E_Price_Earnings_Ratio"],
):
    col = 1
    for cat in colNameLists:
        fig.add_trace(addTrace(cat, report, "gray", mode="lines"), row=5, col=1)
        col += 1
    return fig


def DRAW(df, Report_A, Report_Q, Ma_Day_List=[1], title="", mode="all"):
    """
    绘制
    df = pd.dataframe()
    MA_LIST = Wave.Wave(int)
    keyls = ['close', 'high', 'low', 'open']
    """

    row = 4
    cols = list(set(df.columns.tolist()))
    cols = ColNameSortByNumber(cols)

    # tdic = []
    # for _ in range(row):
    #     tdic.append([{"type": "scatter"}])

    # 添加图片框信息
    fig = go.Figure()

    # plotly 自带的css配色
    CSS_Colours = [
        "yellowgreen",
        "tomato",
        "lightskyblue",
        "lightpink",
        "Aquamarine",
        #    'aliceblue',
        #    'mistyrose',
        "pink",
        "limegreen",
        #    'skyblue',
        "hotpink",
        "cyan",
        "gold",
        "lightsalmon",
        "green",
        "orange",
        "deeppink",
        "Cyan",
        "aqua",
        "aquamarine",
        "azure",
        # 'beige', 'bisque', 'blanchedalmond',
        #    'blueviolet',  'burlywood', 'cadetblue', 'chartreuse', 'chocolate',
        #    'coral', 'cornflowerblue','cornsilk', 'crimson',  'darkblue', 'darkcyan',
        #    'darkgoldenrod', 'darkgray', 'darkgrey', 'darkgreen',
        #    'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange',
        #    'darkorchid', 'darkred', 'darksalmon', 'darkseagreen',
        #    'darkslateblue', 'darkslategray', 'darkslategrey',
        #    'darkturquoise', 'darkviolet',  'deepskyblue',
        #    'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
        #    'forestgreen', 'fuchsia', 'gainsboro','goldenrod',  'grey',
        #    'greenyellow', 'honeydew',  'indianred', 'indigo',
        #    'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
        #    'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
        #    'lightgoldenrodyellow', 'lightgray', 'lightgrey',
        #    'lightgreen', 'lightpink',  'lightseagreen',
        #    'lightslategray', 'lightslategrey',
        #    'lightsteelblue', 'lightyellow', 'lime', 'limegreen',
        #    'linen', 'magenta', 'maroon', 'mediumaquamarine',
        #    'mediumblue', 'mediumorchid', 'mediumpurple',
        #    'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
        #    'mediumturquoise', 'mediumvioletred', 'midnightblue',
        #    'mintcream',  'moccasin', 'navajowhite', 'navy',
        #    'oldlace', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise',
        #    'palevioletred', 'papayawhip', 'peachpuff', 'peru',
        #    'plum', 'powderblue', 'purple', 'red', 'rosybrown',
        #    'royalblue', 'rebeccapurple', 'saddlebrown', 'salmon',
        #    'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver',
        #    'slategray', 'slategrey', 'snow','springgreen',  'tan', 'teal', 'thistle',
        #    'turquoise', 'violet', 'wheat','yellow',
    ]
    # 蜡烛图
    fig.add_trace(
        go.Candlestick(
            x=df["date"],
            open=df["open"],
            high=df["high"],
            low=df["low"],
            close=df["close"],
            text=df["date"],
            name="KD",
            yaxis="y3",
        )
    )
    # 绘制MA波动线
    fig.add_trace(
        addTrace(
            "inPrice",
            df,
            "tomato",
            fill="tozeroy",
            mode=None,
            text=df.loc[:, "TAG"],
            yaxis="y3",
        )
    )
    fig.add_trace(
        addTrace(
            "outPrice",
            df,
            "yellowgreen",
            fill="tozeroy",
            mode=None,
            text=df.loc[:, "TAG"],
            yaxis="y3",
        )
    )

    fig = MainMaTraceAdd(cols, fig, df, CSS_Colours, mode=mode, Ma_Day_List=Ma_Day_List)

    # CSS_Colours

    # fig = MainRepotDetail(Report_A, CSS_Colours, fig, colNameLists=[
    #                       'PE_last_year_ratio', 'P/E_Price_Earnings_Ratio'])
    # fig = MainRepotDetail(Report_Q, CSS_Colours, fig, colNameLists=[
    #                       'PE_TTM'])
    try:
        fig.add_trace(
            go.Scatter(
                x=df["date"],
                y=df["MARKER=B"],
                marker=dict(color="tomato", size=15),
                name="MARKER=B",
                text=df.loc[:, "TYPES"].shift(-1),
                mode="markers",
                yaxis="y3",
            )
        )
        fig.add_trace(
            go.Scatter(
                x=df["date"],
                y=df["MARKER=S"],
                marker=dict(color="yellowgreen", size=15),
                name="MARKER=S",
                text=df.loc[:, "TYPES"].shift(-1),
                mode="markers",
                yaxis="y3",
            )
        )

    except Exception as e:
        print(e)

    fig.add_trace(
        addTrace("TotalValues", df, "tomato", mode="lines", fill="tozeroy", yaxis="y1")
    )

    fig.add_trace(
        addTrace("AvableCash", df, "green", mode="lines", fill="tozeroy", yaxis="y1")
    )

    fig.add_trace(
        go.Scatter(
            x=df["date"],
            y=round(df["winValue"], 2),
            marker=dict(color="#fff"),
            name="startCash",
            text=df["newPresent"],
            mode="lines",
            line=dict(width=0.5, dash="dot"),
            yaxis="y1",
        )
    )

    df.loc[:, "zero"] = 0
    for r in range(row):  # 添加0轴
        a = r + 1
        x = "y" + str(a)
        fig.add_trace(
            go.Scatter(
                x=df["date"],
                y=df["zero"],
                marker=dict(color="black"),
                name="zero",
                text=df.loc[:, "TAG"],
                mode="lines",
                line=dict(width=1, dash="dot"),
                yaxis=x,
            )
        )

    fig.add_trace(
        go.Scatter(
            x=df["date"],
            y=df["Avg"],
            marker=dict(color="orange"),
            name="Avg",
            mode="lines",
            line=dict(width=3),
            yaxis="y3",
        )
    )
    try:
        starts = df.date.iloc[-30]
    except Exception as e:
        print(e)
        starts = df.date.iloc[0]

    fig.update_layout(
        showlegend=True,
        modebar=dict(orientation="h"),
        xaxis_rangeslider_visible=False,
        hovermode="x",
        spikedistance=-1,
        # paper_bgcolor="rgb(0,0,0)",
        # plot_bgcolor="rgb(0,0,0)",
        title=dict(
            text=title,
            font=dict(
                size=15,
                #  color="#C0C0C0"
            ),
        ),
        legend=dict(
            # bgcolor="rgb(0,0,0)",
            # bordercolor="rgb(0,0,0)",
            # borderwidth=10,
            font=dict(
                size=10,
                #  color="#C0C0C0"
            ),
            itemwidth=30,
        ),
        # colorscale=dict(sequential="blackbody"),
        margin=dict(l=0, r=0, t=40, b=0),
        xaxis=dict(
            showspikes=True,
            spikemode="across+toaxis",
            spikesnap="cursor",
            spikedash="dot",
            # color="#696969",
            # gridcolor="rgb(50,50,50)",
            autorange=True,
            range=[starts, df.date.iloc[-1]],
            # rangeslider=dict(autorange=True, range=[df.date.iloc[1], df.date.iloc[-1]]),
            showticklabels=False,
            gridwidth=1,
            scaleanchor="x",
            tickmode="array",
            type="category",
            showline=False,
        ),
        yaxis1=dict(
            ticklabelposition="inside top",
            # gridcolor="rgb(50,50,50)",
            # tickfont=dict(color="#C0C0C0"),
            anchor="x",
            domain=[0, 0.15],
            mirror=True,
            # zeroline=True,
            # zerolinewidth=5,
            # zerolinecolor="rgb(0,0,0)",
            gridwidth=1,
            # showline=True,
            # linewidth=5,
            type="linear",
            title=dict(
                text="y1_收益情况",
                # font=dict(color="#C0C0C0")
            ),
            range=[
                df.AvableCash.min() * 0.8,
                df.TotalValues.max() * 1.2,
            ],
        ),
        yaxis2=dict(
            ticklabelposition="inside top",
            # gridcolor="rgb(50,50,50)",
            # tickfont=dict(color="#C0C0C0"),
            anchor="x",
            domain=[0.15, 0.3],
            mirror=True,
            # zeroline=True,
            # zerolinewidth=5,
            # zerolinecolor="rgb(0,0,0)",
            range=[-1.5, 1.5],
            gridwidth=1,
            title=dict(
                text="y2_Main",
                # font=dict(color="#C0C0C0")
            ),
            type="linear",
            # showline=True,
            # linewidth=5,
        ),
        yaxis3=dict(
            ticklabelposition="inside top",
            # gridcolor="rgb(50,50,50)",
            # tickfont=dict(color="#C0C0C0"),
            anchor="x",
            domain=[0.4, 1],
            mirror=True,
            # zeroline=True,
            # zerolinewidth=5,
            # zerolinecolor="rgb(0,0,0)",
            gridwidth=1,
            # showline=True,
            # linewidth=5,
            type="linear",
            title=dict(
                text="y3_Main_chart",
                # font=dict(color="#C0C0C0")
            ),
            range=[df.low.min() * 0.8, df.high.max() * 1.2],
        ),
        yaxis4=dict(
            ticklabelposition="inside top",
            # gridcolor="rgb(50,50,50)",
            # tickfont=dict(color="#C0C0C0"),
            anchor="x",
            domain=[0.3, 0.4],
            mirror=True,
            # zeroline=True,
            # zerolinewidth=5,
            # zerolinecolor="rgb(0,0,0)",
            gridwidth=1,
            # showline=True,
            # linewidth=5,
            type="linear",
            title=dict(
                text="y4_detail",
                # font=dict(color="#C0C0C0")
            ),
            range=[-1.5, 1.5],
        ),
    )

    # fig.show()
    title = "_".join(title.split(" "))
    title = "".join(title.split("%"))
    title = "".join(title.split(":"))
    title = "".join(title.split("*"))
    fig.write_html("htmls/{}.html".format(title))
